pPing = null
# forced：是否重新做身份验证
W.ping = (forced)->
    return pPing if pPing? and not forced
    pPing = W.api.get 'ping'
    $overlay = $(WCT.AuthOverlay()).appendTo($('body'))
    pPing.then (res)->
        console.log 'ping', res
        $overlay.remove()
        W.user = res
    pPing.caught (jqxhr)->
        console.log 'ping', jqxhr
        $overlay.remove()
    pPing

W.isTouchDevice = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|playbook|silk|BlackBerry|BB10|Windows Phone|Tizen|Bada|webOS|IEMobile|Opera Mini)/);
W.isTouch = (('ontouchstart' in window) || (navigator.msMaxTouchPoints > 0) || (navigator.maxTouchPoints));

W.pSignIn = ->
    pp = W.ping()
    pp.caught -> W.toSignIn()

# 显示登录对话框
W.toSignIn = ->
    dialog = W.showDialog WCT.SignIn()
    $tip = $('.tip', dialog.$modal)

    return new Promise (resolve, reject)->
        $('.do-sign-in', dialog.$modal).click ->
            $this = $(this)
            $tip.html '正在登录，请稍后...'
            $this.hide()

            username = $.trim $('input[name="username"]', dialog.$modal).val()
            password = $.trim $('input[name="password"]', dialog.$modal).val()

            q = W.api.post 'sign-in', {username, password}
            q.then (res)->
                W.user = res
                $tip.html '登录成功'
                resolve()
                W.setTimeout 500, -> dialog.close()

            q.caught (jqxhr)->
                reject()
                ae = W.getAppError jqxhr
                if ae
                    $tip.html ae.defaultMessage
                else
                    $tip.html "服务器错误（#{jqxhr.status}）"
                $this.show()
            q.lastly ->
                W.ping(true)

W.signOut = ->
    return new Promise (resolve, reject)->
        q = W.api.post 'sign-out'
        q.then (res)->
            W.user = null
            location.href = "/sign-in"
        q.caught (jqxhr)->
            reject()
        q.lastly ->
            W.ping(true)

W.getAppError = (jqxhr)->
    try
        JSON.parse jqxhr.responseText
    catch
        null

W.alertAjaxError = (jqxhr)->
    ae = W.getAppError jqxhr
    if ae
        W.toastError ae.defaultMessage || ae.message
    else if jqxhr.status == 403
        W.toastError "权限不够！"
    else
        W.toastError "服务器错误（#{jqxhr.status}）"

W.setTimeout = (timeout, callback)-> setTimeout(callback, timeout)

W.preventDefault = (e)->
    e.preventDefault()
    e.stopImmediatePropagation()
    e.stopPropagation()
    e

toastTime = 0
toast = (message, level, time)->
    clearTimeout(toastTime)
    $("body>.toast").remove()
    $toast = $ "<div>",
        class: "toast toast-#{level}"
    $content = $ "<div>",
        class: "toast-content",
        html: message
    $toast.html $content
    $toast.appendTo $("body").show()

    toastTime = setTimeout (-> $toast.fadeOut(200).remove()), time

W.toastError = (message, time)->
    swal("error", message, "error");
#    toast(message, "error", time = 3000)
W.toastInfo = (message, time)->
    swal("success", message, "success")
#    toast(message, "info", time = 3000)
W.toastWarning = (message, time)->
    swal({   title: message, timer: 2000,   showConfirmButton: false });
#    toast(message, "warning", time = 3000)

W.toYMDHM = (date) ->
    return unless date
    date = new Date date
    return date && date.getYear && ((date.getFullYear()) + "-" + (date.getMonth() + 1) + "-" + (date.getDate()) + " " + (date.getHours()) + ":" + (date.getMinutes()));

W.toYMD = (date) ->
    return unless date
    date = new Date date
    return date && date.getYear && ((date.getFullYear()) + "-" + (date.getMonth() + 1) + "-" + (date.getDate()));